package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.LoginMapper;
import com.heima.admin.service.LoginService;
import com.heima.model.admin.dots.LoginADto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdUser> implements LoginService {

    private final LoginMapper loginMapper;

    @Override
    public ResponseResult login(LoginADto dto) {
//        判断用户名和密码是否为空
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "账号或密码为空！");
        }

//        查出用户
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName());
        AdUser apUserA = loginMapper.selectOne(wrapper);
//        如果为为空 用户不存在
        if (apUserA == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "用户不存在！");
        }

//        拿出用户对应密码
        String password = apUserA.getPassword();

//        拿出前端输入的密码 并进行加盐 与md5加密
        String md5Password = DigestUtils.md5DigestAsHex((dto.getPassword() + apUserA.getSalt()).getBytes());

//        判断是否相等
        if (!md5Password.equals(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "用户名或密码错误！！！");
        }

        JSONObject result = new JSONObject();
        apUserA.setSalt(null);
        apUserA.setPassword(null);
        result.put("user", apUserA);
        result.put("token", AppJwtUtil.getToken(apUserA.getId().longValue()));

        return ResponseResult.okResult(result);
    }
}
